// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 初始化搜索功能
    initSearch();

    // 初始化添加电影表单
    initAddMovieForm();

    // 初始化分类筛选
    initCategoryFilter();
});

// 删除电影函数
function deleteMovie(movieId) {
    if (confirm('确定要删除这部电影吗？')) {
        // 显示加载状态
        const deleteBtn = event.currentTarget;
        const originalHtml = deleteBtn.innerHTML;
        deleteBtn.disabled = true;
        deleteBtn.innerHTML = '<span class="loading-spinner"></span>';

        // 发送删除请求
        fetch(`/movies/${movieId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
            .then(response => {
                if (response.ok) {
                    // 删除成功，移除元素或刷新页面
                    const movieCard = deleteBtn.closest('.col');
                    if (movieCard) {
                        movieCard.style.opacity = '0';
                        setTimeout(() => {
                            movieCard.remove();
                            checkEmptyState();
                        }, 300);
                    } else {
                        location.reload();
                    }
                    showNotification('电影删除成功！', 'success');
                } else {
                    throw new Error('删除失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('删除失败，请重试！', 'error');
                deleteBtn.disabled = false;
                deleteBtn.innerHTML = originalHtml;
            });
    }
}

// 初始化搜索功能
function initSearch() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            const searchTerm = this.value.toLowerCase();
            const movieCards = document.querySelectorAll('.movie-card');

            let visibleCount = 0;

            movieCards.forEach(card => {
                const title = card.querySelector('.card-title')?.textContent.toLowerCase() || '';
                const genre = card.querySelector('.text-muted')?.textContent.toLowerCase() || '';

                const cardCol = card.closest('.col');
                if (title.includes(searchTerm) || genre.includes(searchTerm)) {
                    cardCol.style.display = '';
                    visibleCount++;
                } else {
                    cardCol.style.display = 'none';
                }
            });

            checkEmptyState(visibleCount);
        });
    }
}

// 初始化添加电影表单
function initAddMovieForm() {
    const saveBtn = document.getElementById('saveMovieBtn');
    if (saveBtn) {
        saveBtn.addEventListener('click', function () {
            // 获取表单数据
            const formData = {
                title: document.getElementById('movieTitle')?.value,
                year: document.getElementById('movieYear')?.value,
                genre: document.getElementById('movieGenre')?.value,
                rating: document.getElementById('movieRating')?.value,
                poster_url: document.getElementById('moviePoster')?.value,
                description: document.getElementById('movieDescription')?.value
            };

            // 表单验证
            if (!validateForm(formData)) {
                return;
            }

            // 显示加载状态
            const originalText = saveBtn.textContent;
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';

            // 发送添加请求
            fetch('/movies', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify(formData)
            })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    }
                    throw new Error('添加失败');
                })
                .then(data => {
                    showNotification('电影添加成功！', 'success');

                    // 关闭模态框并重置表单
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addMovieModal'));
                    modal.hide();
                    document.getElementById('addMovieForm')?.reset();

                    // 刷新页面或添加新卡片
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('添加失败，请重试！', 'error');
                    saveBtn.disabled = false;
                    saveBtn.textContent = originalText;
                });
        });
    }
}

// 初始化分类筛选
function initCategoryFilter() {
    const categoryButtons = document.querySelectorAll('.btn-group .btn');
    categoryButtons.forEach(btn => {
        btn.addEventListener('click', function () {
            // 切换活跃状态
            categoryButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            // 获取筛选类别
            const category = this.textContent.trim();

            // 执行筛选
            filterMoviesByCategory(category);
        });
    });
}

// 按类别筛选电影
function filterMoviesByCategory(category) {
    if (category === '全部') {
        document.querySelectorAll('.col').forEach(col => col.style.display = '');
        return;
    }

    let visibleCount = 0;

    document.querySelectorAll('.movie-card').forEach(card => {
        const genreText = card.querySelector('.text-muted')?.textContent || '';
        const cardCol = card.closest('.col');

        if (genreText.includes(category)) {
            cardCol.style.display = '';
            visibleCount++;
        } else {
            cardCol.style.display = 'none';
        }
    });

    checkEmptyState(visibleCount);
}

// 表单验证
function validateForm(data) {
    for (const key in data) {
        if (!data[key]) {
            showNotification(`请填写${getFieldName(key)}字段！`, 'error');
            return false;
        }
    }

    // 年份验证
    const year = parseInt(data.year);
    if (isNaN(year) || year < 1900 || year > new Date().getFullYear() + 5) {
        showNotification('请输入有效的上映年份！', 'error');
        return false;
    }

    // 评分验证
    const rating = parseFloat(data.rating);
    if (isNaN(rating) || rating < 0 || rating > 10) {
        showNotification('请输入0-10之间的评分！', 'error');
        return false;
    }

    return true;
}

// 获取字段名称
function getFieldName(field) {
    const fieldNames = {
        'title': '电影名称',
        'year': '上映年份',
        'genre': '类型',
        'rating': '评分',
        'poster_url': '海报URL',
        'description': '简介'
    };
    return fieldNames[field] || field;
}

// 检查空状态
function checkEmptyState(visibleCount) {
    const movieCols = document.querySelectorAll('.col');
    const totalMovies = movieCols.length;

    // 如果没有指定可见数量，则重新计算
    if (typeof visibleCount === 'undefined') {
        visibleCount = 0;
        movieCols.forEach(col => {
            if (col.style.display !== 'none') visibleCount++;
        });
    }

    const emptyState = document.querySelector('.empty-state');

    if (visibleCount === 0) {
        if (!emptyState) {
            // 创建空状态元素
            const emptyStateHtml = `
                <div class="col-12 text-center py-5 empty-state">
                    <div class="empty-state-content">
                        <i class="fas fa-film text-muted" style="font-size: 5rem;"></i>
                        <h3 class="mt-3 text-muted">暂无电影数据</h3>
                        <p class="text-muted">点击"添加电影"按钮添加新电影</p>
                        <button class="btn btn-primary mt-3" data-bs-toggle="modal" data-bs-target="#addMovieModal">
                            <i class="fas fa-plus-circle me-1"></i>添加电影
                        </button>
                    </div>
                </div>
            `;
            document.querySelector('.row.g-4').insertAdjacentHTML('beforeend', emptyStateHtml);
        }
    } else if (emptyState) {
        emptyState.remove();
    }
}

// 显示通知
function showNotification(message, type) {
    // 检查是否已有通知元素
    let notification = document.getElementById('notification');

    if (!notification) {
        // 创建通知元素
        notification = document.createElement('div');
        notification.id = 'notification';
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.zIndex = '9999';
        notification.style.transition = 'all 0.3s ease';
        document.body.appendChild(notification);
    }

    // 创建通知项
    const notificationItem = document.createElement('div');
    notificationItem.className = `alert ${type === 'success' ? 'alert-success' : 'alert-danger'} alert-dismissible fade show`;
    notificationItem.style.marginBottom = '10px';
    notificationItem.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;

    notification.appendChild(notificationItem);

    // 自动关闭
    setTimeout(() => {
        notificationItem.style.opacity = '0';
        setTimeout(() => {
            notificationItem.remove();
            if (notification.children.length === 0) {
                notification.remove();
            }
        }, 300);
    }, 3000);
}

// 获取Cookie
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}